/**
 * @author gykl 下拉树 需要库包括 
 * jquery-ui.js buss.panel.js buss.combo.js
 *         buss.tree.js 
 */
(function($,undefined){

	$.widget("ui.combotree",{
		options:{
			width:'auto',
			panelWidth:null,
			panelHeight:200,
			valueCol:'id',
			textCol:'name',
			splitSymbol:',',
			editable:false,
			topTools:[],
			bottomTools:[],
			treeSetting:{
				checkable: false,
				showLine: true,
				checkStyle: 'checkbox',
				checkRadioType:"all",
				checkedCol: "checked",
				async: false,
				asyncUrl: "",
				asyncDataCol:"result",
				asyncParam: [],
				asyncParamOther: [],
				treeNodeKey: "",
				treeNodeParentKey: "",
				hasChildKey:"hasChild",
				nameCol: "name",
				nodesCol: "nodes",
				checkedCol: "checked", 
				callback: {
					click:null,
					onSelectBefore:null,
					onSelected:null,
					asyncSuccess:null,
					asyncError:null,
					nodeCreated:null
				}
			}
		},
		_create:function(){
			this.comboSpan = $("<span class='buss-combo'/>").insertAfter(this.element);
			this.element.addClass("buss-combo-value").hide().appendTo(this.comboSpan);
			$("<input class='buss-combo-text' type='text'/>").appendTo(this.comboSpan);
			$("<span><span class='buss-combo-arrow'></span></span>").appendTo(this.comboSpan);
			this.comboPanel = $("<div class='buss-combo-panel' style='position:absolute;display:block;'/>");
			var treePanel = $("<ul class='buss-treepanel tree'></ul>");
			this.comboPanel.append(treePanel);
		},
		_init:function(){
			var _self = this;
			var opts = this.options;
			var _width = this.element.outerWidth();
			
			if (!opts.editable){
				this.comboSpan.find(".buss-combo-text").attr("readonly","readonly");
			}
			
			if(opts.width != 'auto'){
				_width = opts.width;
			}
			this.comboSpan.find(".buss-combo-text").css("width",_width - this.comboSpan.find(".buss-combo-arrow").outerWidth());
			var _panelWidth = 0;
			if(opts.panelWidth == null){
				_panelWidth = _width + 2;
			}else{
				_panelWidth = opts.panelWidth + 2;
			}			
			
			this.comboPanel.panel({
				width:_panelWidth,
				height:opts.panelHeight,
				topTools:opts.topTools,
				bottomTools:opts.bottomTools,
				onRestore:function(){
					var zIndex = parseInt(_self.comboPanel.css('z-index'));
					zIndex = isNaN(zIndex) ? 0 : zIndex;
					var maxZIndex = $.maxZIndex();
					if (maxZIndex == 0 || maxZIndex > zIndex){
						_self.comboPanel.css("z-index",maxZIndex + 1);
					}					
					var vals = _self.element.val();
					_self.selectNodes(vals);
					_self._setPosition();
				}
			});
			this.comboPanel.find(".buss-panel-body").addClass("buss-combo-panel-topborder");
			
			
			opts.treeSetting.callback.click = function(event,treeObjId,treeNode){
				var textKey = opts.textCol;
				if($.isFunction(opts.treeSetting.callback.onSelectBefore)){
					if(opts.treeSetting.callback.onSelectBefore.call(_self.comboPanel,treeNode) == false) return;
				}
				
				_self.comboSpan.find(".buss-combo-text").val(treeNode[textKey]);		
				_self.element.val(treeNode[opts.valueCol]);
				_self.comboPanel.panel("close");
				
				if($.isFunction(opts.treeSetting.callback.onSelected)){
					
					opts.treeSetting.callback.onSelected.call(_self.comboPanel,treeNode);
				}
			}
			
			this.comboTree = this.comboPanel.find(".buss-treepanel").zTree(opts.treeSetting,opts.treeSetting.treeData);
			
			this.updateText();
			this.element.unbind("_destroy.buss");
			this.element.bind("_destroy.buss",function(){
				_self.comboPanel.remove();
			})
			
			this.comboPanel.panel("close");
			this._bindEvents();
		},
		getSelectedNode:function(){
			var node = this.comboTree.getSelectedNode();
			alert(node.name);
		},
		_setPosition:function(){
			var inputOffset = this.comboSpan.offset();
			var bottomGap = $(window).height() - inputOffset.top + this.comboSpan.outerHeight();
			
			if(inputOffset.top >= this.comboPanel.outerHeight() && bottomGap <= this.comboPanel.outerHeight()){
				this.options._pos = "top";
				var top = inputOffset.top - this.comboPanel.outerHeight() + 3;
				var left = inputOffset.left;		
				this.comboPanel.css({top:top,left:left});
				this.comboPanel.find(".buss-panel-top-toolbar").css("border-top","1px solid #B2C8D0");
			}else{
				this.options._pos = "bottom";
				var top = inputOffset.top + this.comboSpan.height() + 2;
				var left = inputOffset.left;		
				this.comboPanel.css({top:top,left:left});
			}		
		},
		getValueAndText:function(){
			var text = this.comboSpan.find(".buss-combo-text").val();
			var value = this.element.val();
			return {text:text,value:value};
		},
		selectNodes:function(values,checkTypeFlag){
			if ($.trim(values) == "") return;
			var tmpVals = values.split(this.options.splitSymbol);
			var tmpValsLen = tmpVals.length;
			var key = this.options.valueCol;			
			if (tmpValsLen == 1){				
				var node = this.comboTree.getNodeByParam(key,tmpVals[0]);
				if (!node){
					return;
				}
				this.comboTree.selectNode(node);
			}else{
				for (var i = 0;i < tmpValsLen;i++){
					var node = this.comboTree.getNodeByParam(key,tmpVals[i]);
					if(!node) continue;
					if(this.options.treeSetting.checkable){
						node[this.options.treeSetting.checkedCol] = true;
						this.comboTree.updateNode(node,checkTypeFlag);						
					}else{
						this.comboTree.selectNode(node);
					}
				}
			}
		},
		updateText:function(){
			var text = "";
			var value = this.element.val();
			if($.trim(value) == "") return;
			var tmpVals = value.split(this.options.splitSymbol);
			var tmpValsLen = tmpVals.length;
			var key = this.options.valueCol;
			if(tmpValsLen == 1){
				var node = this.comboTree.getNodeByParam(key,tmpVals[0]);
				if(!node){
					return;
				}
				this.comboSpan.find(".buss-combo-text").val(node[this.options.textCol]);
			}else{
				this.comboSpan.find(".buss-combo-text").val("");
				for(var i = 0;i < tmpValsLen;i++){
					var node = this.comboTree.getNodeByParam(key,tmpVals[i]);
					if(!node) continue;
					var tmpText = this.comboSpan.find(".buss-combo-text").val();
					if(tmpText == ""){
						this.comboSpan.find(".buss-combo-text").val(node[this.options.textCol]);
					}else{
						this.comboSpan.find(".buss-combo-text").val(tmpText + this.options.splitSymbol + node[this.options.textCol]);
					}
				}
			}
		},
		reAsyncChildNodes:function(parentNode,reloadType){
			this.comboTree.reAsyncChildNodes(parentNode,reloadType);
		},
		getTree:function(){
			return this.comboTree;
		},
		_bindEvents:function(){
			var _self = this;
			$("dobument").unbind(".combotree");
			_self.comboPanel.unbind(".combotree");
			_self.comboSpan.find(".buss-combo-text").unbind(".combotree");
			_self.comboSpan.find(".buss-combo-arrow").unbind(".combotree");
			
			$(document).bind("mousedown.combotree",function(e){						
				_self.comboPanel.panel("close");
			})
			
			_self.comboPanel.bind('mousedown.combotree',function(e){
				e.stopPropagation();
				return false;
			})
			
			_self.comboSpan.find(".buss-combo-text").bind("focus.combotree",function(e){				
				_self.comboPanel.panel("restore");
			}).bind("mousedown.combotree",function(e){			
				e.stopPropagation();		
			}).bind('keyup.combo',function(e){
				switch(e.keyCode){
					case $.ui.keyCode.LEFT:
					case $.ui.keyCode.UP:
						if (_self.comboPanel.panel("option",'minimized') == true){
							_self.comboPanel.panel("restore");
							return;
						};
						break;
					case $.ui.keyCode.RIGHT:
					case $.ui.keyCode.DOWN:
						if (_self.comboPanel.panel("option",'minimized') == true){
							_self.comboPanel.panel("restore");
							return;
						}
						break;
					case $.ui.keyCode.ESCAPE:
						_self.comboPanel.panel("close");
						break;					
				}
			})
			
			_self.comboSpan.find(".buss-combo-arrow").bind("click.combotree",function(){
				_self.comboSpan.find(".buss-combo-text").focus();
			});
		},
		
	})
})(jQuery)
